package com.live.activity;

import java.io.StringWriter;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;

import org.xmlpull.v1.XmlSerializer;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Vibrator;
import android.util.Xml;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.live.common.LiveImageHelper;
import com.live.receiver.LiveReceiver;
import com.live.tools.LiveTools;

public class LiveAlarmActivity extends LiveBaseActivity {

	private LiveImageHelper image = null;
	private MediaPlayer alarmSound = null;
	private Vibrator vibrator = null;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.live_alarm);

		Date date = new Date(System.currentTimeMillis());
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		String today = df.format(date);

		/* 获取Intent中的Bundle对象 */
		Bundle bundle = this.getIntent().getExtras();
		String matchId = bundle.getString("matchId");

		// 取得现有提醒表
		List<Map<String, Object>> liveAlarmList = LiveTools.readLiveAlarmFile(context,
				"alarm_" + today + ".xml".toString());

		// 取得现有提醒表长度
		int liveAlarmLength = liveAlarmList.size();
		for (int i = 0; i < liveAlarmLength; i++) {

			Map<String, Object> alarm = liveAlarmList.get(i);

			// 取得当前提醒比赛
			if (matchId.equals(alarm.get("matchId").toString())) {

				// 设定提醒画面信息
				TextView matchTime = (TextView) findViewById(R.id.matchTime);
				String time = alarm.get("matchTime").toString();
				time = time.substring(11, 16).replace(",", ":");
				matchTime.setText(time);
				TextView matchName = (TextView) findViewById(R.id.matchName);
				matchName.setText(alarm.get("matchName").toString());
				TextView homeTeam = (TextView) findViewById(R.id.homeTeam);
				homeTeam.setText(alarm.get("homeTeam").toString());
				ImageView homeTeamPic = (ImageView) findViewById(R.id.homeTeamPic);
				image = new LiveImageHelper(homeTeamPic);
				image.execute(alarm.get("homeTeamPic").toString());
				TextView visitTeam = (TextView) findViewById(R.id.visitTeam);
				visitTeam.setText(alarm.get("visitTeam").toString());
				ImageView visitTeamPic = (ImageView) findViewById(R.id.visitTeamPic);
				image = new LiveImageHelper(visitTeamPic);
				image.execute(alarm.get("visitTeamPic").toString());

				// 创建AlarmManager
				@SuppressWarnings("static-access")
				AlarmManager am = (AlarmManager) context.getSystemService(context.ALARM_SERVICE);

				// 为系统添加定时提醒
				PendingIntent pi = PendingIntent.getBroadcast(context,
						Integer.valueOf(alarm.get("matchId").toString()), new Intent(context, LiveReceiver.class), 0);

				// 从系统中删除已经添加的定时提醒
				am.cancel(pi);

				// 删除此提醒
				liveAlarmList.remove(i);

				break;
			}
		}

		if (liveAlarmList.size() == 0) {
			LiveTools.deleteFile(context, null, "alarm_" + today + ".xml");
		} else {
			// 写入本机缓存数据（XML）
			LiveTools.writeFile(context, "alarm_" + date + ".xml".toString(), buildXml(liveAlarmList));
		}

		TextView liveAlarmBtn = (TextView) findViewById(R.id.liveAlarmBtn);
		liveAlarmBtn.setOnClickListener(new TextView.OnClickListener() {
			public void onClick(View v) {

				// 停止提示音
				alarmSound.stop();

				// 停止震动
				vibrator.cancel();

				// 关闭当前窗口
				finish();

				if (LiveBaseActivity.activityList.size() == 1) {

					// 运行主程序
					Intent intent = new Intent();
					intent.setClass(context, LiveWelcomeActivity.class);
					context.startActivity(intent);
				}
			}
		});

		// 播放提示音
		alarmSound = MediaPlayer.create(this, R.raw.alarm);
		alarmSound.start();// 开始或恢复播放

		// 开始震动
		vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
		long[] pattern = { 500, 1500, 500, 1500 }; // 根据指定的模式进行震动
		// 第一个参数：该数组中第一个元素是等待多长的时间才启动震动，
		// 之后将会是开启和关闭震动的持续时间，单位为毫秒
		// 第二个参数：重复震动时在pattern中的索引，如果设置为-1则表示不重复震动<p>
		// 启动震动，并持续指定的时间
		vibrator.vibrate(pattern, 2);
		// -1不重复，非-1为从pattern的指定下标开始重复
	}

	private String buildXml(List<Map<String, Object>> matchList) {
		XmlSerializer serializer = Xml.newSerializer();
		StringWriter writer = new StringWriter();
		try {
			serializer.setOutput(writer);

			// <?xml version="1.0″ encoding="UTF-8″ standalone="yes"?>
			serializer.startDocument("UTF-8", true);
			// <liveScore number="1″>
			serializer.startTag(null, "matchs");
			for (int i = 0; i < matchList.size(); i++) {
				Map<String, Object> match = matchList.get(i);

				// <detail>
				serializer.startTag(null, "match");

				// <matchId>
				serializer.startTag(null, "matchId");
				serializer.text(String.valueOf(match.get("matchId")));
				serializer.endTag(null, "matchId");

				// <matchTime>
				serializer.startTag(null, "matchTime");
				String matchTime = String.valueOf(match.get("matchTimeAll"));
				matchTime = matchTime.replaceAll("-", ",");
				matchTime = matchTime.replaceAll(" ", ",");
				matchTime = matchTime.replaceAll(":", ",");
				serializer.text(matchTime);
				serializer.endTag(null, "matchTime");

				// <matchName>
				serializer.startTag(null, "matchName");
				String matchName = String.valueOf(match.get("matchName"));
				serializer.text(matchName);
				serializer.endTag(null, "matchName");

				// <homeTeam>
				serializer.startTag(null, "homeTeam");
				String homeTeam = String.valueOf(match.get("homeTeam"));
				serializer.text(homeTeam);
				serializer.endTag(null, "homeTeam");

				// <visitTeam>
				serializer.startTag(null, "visitTeam");
				String visitTeam = String.valueOf(match.get("visitTeam"));
				serializer.text(visitTeam);
				serializer.endTag(null, "visitTeam");

				// <homeTeamPic>
				serializer.startTag(null, "homeTeamPic");
				String homeTeamPic = String.valueOf(match.get("homeTeamPic"));
				serializer.text(homeTeamPic);
				serializer.endTag(null, "homeTeamPic");

				// <visitTeamPic>
				serializer.startTag(null, "visitTeamPic");
				String visitTeamPic = String.valueOf(match.get("visitTeamPic"));
				serializer.text(visitTeamPic);
				serializer.endTag(null, "visitTeamPic");

				serializer.endTag(null, "match");
			}
			serializer.endTag(null, "matchs");
			serializer.endDocument();

			return writer.toString();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}